package Server1;
import java.net.*;
import java.io.*;
import java.lang.Thread;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Hashtable;
import java.util.Vector;
import java.sql.*;
import java.util.Hashtable;
import java.util.Vector;

// lop de thuc hien phan hoi cho Server khac hoac tu client gui den
class Handler extends Thread{

	Socket client;
	String serverName;
	String type;
	int demtenfile;

	int pos;
	RountingTable rount;
	public int currentCircle;
	public String MESSAGE;
	Hashtable hash;
	
 	DataOutputStream 	out;
 	BufferedReader 		in;
		
	public Handler(Socket newSocket,String serverName,int pos, int curr, Hashtable hash){
		client=newSocket;
		this.serverName = serverName;
		rount = new RountingTable();
		this.pos = pos;
		this.currentCircle = curr;
		MESSAGE ="";
		this.hash = hash;
	}

	public void run()
	{
		try
		{
			String destName = client.getInetAddress().getHostName();
			int destPort = client.getPort();
			System.out.println("Accepted connection from "+destName +" on port "+destPort+".");
			demtenfile=0;
			
			BufferedReader inStream = new BufferedReader(
	      		new InputStreamReader(client.getInputStream()));
	      			
	      	DataOutputStream outStream = new
	           	DataOutputStream(client.getOutputStream());
	           	
	        boolean finished = false;
	       
	        
	    	// lay goi tin nhan duoc
	    	String inLine = inStream.readLine();
	    	// tao doi tuong RecievedMessageProcessing de phan tich goi tin
	    	RecievedMessageProcessing re = new RecievedMessageProcessing(inLine);
	    	
	    	String st = re.getStart();
	    	String je = re.getJeton();
	    	String lamport = re.getLamport();
	    	String name = re.getServerName();
	    	String type = re.getType();
	    	String action = re.getAction();
	    	String circle = re.getNumCircle();
	    	String message = re.getMessage();
	    	MESSAGE = message;
	    	String jeton;
	    	
	     	int start = Integer.parseInt(st);
	     	int act = Integer.parseInt(action);
	  	
	    	String t = "", rev;
	    	
	    	if (act==4) {
	    		rev=je;
	        	int po=pos+9;
	        	//rev +="1";
	        	try
	        	{
	        		rev = je.substring(1,po);
	        		}            	
	        		catch(Exception ex){}
	        		t=rev;
	        		//System.out.println("Jeton cua act=4 : "+t);
	        	}
	    	else
	    	if (act==3) {
	    		try
	        	{
	        		t = je.substring(0,pos-1);
	        	}            	
	        	catch(Exception ex){}
	        	
				jeton=je;
	        	t +="1";
	        	try
	        	{
	        		t += jeton.substring(pos);
	        		}            	
	        		catch(Exception ex){}
	        		//System.out.println("Jeton cua act=3 : "+t);
	        	}
	    	else            	
	    	if (act==2) {
	    		try
	        	{
	        		t = je.substring(0,pos-1);
	        	}            	
	        	catch(Exception ex){}
	        	
				jeton=je;
	        	t +="1";
	        	try
	        	{
	        		t += jeton.substring(pos);
	        		}            	
	        		catch(Exception ex){}
	        		//System.out.println("Jeton cua act=2 : "+t);
	  		}
	    	else
	    		if (act==1) {
	    			try
	            	{
	            		t = je.substring(0,pos-1);
	            	}            	
	            	catch(Exception ex){}
	            	
	    			jeton=je;
	            	t +="1";
	            	try
	            	{
	            		t += jeton.substring(pos);
	            		}            	
	            		catch(Exception ex){} 
	            		//System.out.println("Jeton cua act=1"+t);
	            	}
	    		int vt = pos;
	    		if (vt>rount.max-1)
	    			vt=0;
	    		
	     		
	//    	 xu ly thong tin tu client
	   	   if (start==0)
	   	   	{
	   			start++;
	   			String replyClientMessage = this.serverName + "  Hoan tat dang ky";
	        	for(int i=0;i<replyClientMessage.length();++i)
	        		outStream.write((byte)replyClientMessage.charAt(i));
	        	System.out.println("Reply: " + replyClientMessage+"\n");
	        	
			
	        	try
	        	{	            	
		        	ConnectToServer co = new ConnectToServer(rount.table[vt].destination,rount.table[vt].port,rount.table[vt].name);
		        	co.connect();	            		
		        	co.requestServer("@$"+start+"|"+t+"|"+lamport+"|"+rount.table[pos-1].name+"|"+"Locked"+"|"+act+"|"+circle+"$$"+message+"$@");
		        	co.shutdown();
		        	
	   			}
	        	
	        	//bi su co
	    		catch(Exception ex)
	    		{
	        		System.out.println("\n"+rount.table[vt].name+": bi su co , hien khong lien lac duoc. Qua trinh dang ki khong thanh cong\n");
					
					// Thong bao cho Client la dang ki khong thanh cong
	        		
	        		Socket ClientSocket = new Socket("Localhost", 2000);
			        //tao luong gui du lieu len server ( server o day chinh la client )
			        DataOutputStream outToServer = new DataOutputStream(ClientSocket.getOutputStream());
			        //gui len server
			        outToServer.writeBytes("Qua trinh dang ki khong thanh cong"+'\n');
			        
	        	} 
	           } 	//end if
		           //ket thuc xu ly tu client
		 
	//  xu ly thong tin temped, nhan thong tin tu server 2 tra nguoc lai, bat dau cap nhat csdl va thong bao cho 
		            	    
			if (type.equals("Temped")&&(start==2))
	 	    {
	     		int stt=start;
	  			System.out.println("Cap nhat CSDL tai Server 1 thanh cong, gui thong bao cho Client !");
							//
	  			stt=1;
	  			act+=1;
	    		try
	       		{	
	       			
		        	// Cap nhat CSDL
    	       		//+++++++++++++++++++++++++++++++
    	       		//++
    	       		
    	       		try
    	       		{
						String[] dulieu = message.split("\\|");
						int sove = Integer.parseInt(dulieu[7]);
						Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
						String url3 = "jdbc:odbc:TOUR";
						Connection dbcn3 = DriverManager.getConnection(url3);
						Statement dbst3 = dbcn3.createStatement();
			     		ResultSet rs3=null;
				  		rs3 = dbst3.executeQuery("insert into dangky (HoVaTen, SoHoChieu, SoCMND, Diachi, Phone, Email, Tour, Sove) values ('"+dulieu[0]+"','"+dulieu[1]+"','"+dulieu[2]+"','"+dulieu[3]+"','"+dulieu[4]+"','"+dulieu[5]+"','"+dulieu[6]+"','"+sove+"')");
						
					}
					catch(Exception e3)
					{
						e3.printStackTrace();
					}
    	       		
    	       		
    	       		//------------------------------
    	       		//--
		        	
		        	//
		        	
		        	// Thong bao cho Client la dang ki thanh cong
		        	Socket ClientSocket = new Socket("Localhost", 2000);
			        //tao luong gui du lieu len server ( server o day chinh la client )
			        DataOutputStream outToServer = new DataOutputStream(ClientSocket.getOutputStream());
			        //gui len server
			        outToServer.writeBytes("Chuc mung ban da dang ki THANH CONG tua du lich nay."+'\n');
		        	
	 	          
	       		}
	           	//bi su co
	       		catch(Exception ex)
	           	{
	           		
					System.out.println("\n"+rount.table[vt].name+": bi su co , hien khong lien lac duoc. Qua trinh dang ki khong thanh cong\n");
					
					// Thong bao cho Client la dang ki khong thanh cong
					Socket ClientSocket = new Socket("Localhost", 2000);
			        //tao luong gui du lieu len server ( server o day chinh la client )
			        DataOutputStream outToServer = new DataOutputStream(ClientSocket.getOutputStream());
			        //gui len server
			        outToServer.writeBytes("Qua trinh dang ki khong thanh cong"+'\n');
	        	
	        	}
	     }//dong if
	 	     	   
	    outStream.write(13);
		outStream.write(10);
		outStream.flush();    			
	
		}//try
		catch(Exception e)	{}

	}//run

}//class